package ru.myrtle.jst.parser;

import java.util.ArrayList;
import java.util.List;

/**
 * Represent line information. Each line has a buffer relative offset of its first
 * character (start), and a buffer relative offset of its line separator (end).
 */
class Line {

    private final int number;
    private final int start;
    private final int end;

    public Line(int number, int start, int end) {
        this.number= number;
        this.start = start;
        this.end = end;
    }

    public int getNumber() {
        return number;
    }
    
    public final int getStart() {
        return start;
    }

    public final int getEnd() {
        return end;
    }

    public int getColumn(int position) {
        return position - start;
    }

    /*
     *
     */

    /**
     * Return an array of Line objects describing the lines of the passed string. The
     * code recognizes the following line separators:
     * <bl>
     * <li>\r - MAC/OS</li>
     * <li>\n - Unix/Linux</li>
     * <li>\r\n - Windows</li>
     * </bl>
     * If the last line lacks a separator, then an empty separator is assumed.
     *
     * @param string string to split into lines.
     * @return list of Line objects. The list will be empty if <code>string</code> is empty.
     */
    public static List<Line> buildLineList(String string) {
        List<Line> list = new ArrayList<Line>();

        int length = string.length();
        int start = 0;
        int number = 1;

        String separator;

        for (int i = 0; i < length; i++) {
            switch (string.charAt(i)) {
                case '\r':
                    if (i + 1 < length && string.charAt(i + 1) == '\n') {
                        separator = "\r\n";
                    }
                    else {
                        separator = "\r";
                    }
                    break;
                case '\n':
                    separator = "\n";
                    break;
                default:
                    continue;
            }

            Line line = new Line(
                    number++, start, i
            );
            list.add(line);

            if (separator.length() == 2) {
                i++;
            }

            start = i + 1;
        }

        if (start < length) {
            Line line = new Line(
                    number, start, length
            );
            list.add(line);
        }

        return list;
    }
}